local extension = Package("heroes_ev4")
extension.extensionName = "evolution"
--extension.game_modes_whitelist = {"brokenroyal_mode"}

local EV = require "packages/evolution/EV"
local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["heroes_ev4"] = "新约角色13-16",
  ["ev"] = "新约",
}

local Yuuka = General(extension, "ev__yuuka", "ev", 4, 4, General.Female)

local huaniaofengyue_trigger = fk.CreateTriggerSkill{
  name = "#huaniaofengyue_trigger",
  events = {fk.EventPhaseStart},
  derived_piles = {"huaniaofengyue"},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local shown = U.getMark(player, "@$shown")
    local cards = room:askForCard(player, 1, 999, true, self.name, true, tostring(Exppattern{ id = shown }), "#huaniaofengyue-put")
    if #cards > 0 then
      player:addToPile("huaniaofengyue", cards, true, self.name)
    end
    local unshown = table.filter(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getMark("@@shown-inhand") == 0 end)
    local shows = room:askForCard(player, 1, 999, true, self.name, true, tostring(Exppattern{ id = unshown }), "#huaniaofengyue-show")
    if #shows > 0 then
      EV.OpenCards(room, player, shows, self.name)
    end
  end,
}

local huaniaofengyue = fk.CreateViewAsSkill{
  name = "huaniaofengyue",
  pattern = "^nullification",
  interaction = function()
    local all_names = {"ev__slash","ev__jink","ev__peach","ev__poison"}
    local names = {}
    local cards = Self:getPile("huaniaofengyue")
    if table.find(cards, function (id) return Fk:getCardById(id).suit == Card.Heart end) then table.insertIfNeed(names, "ev__peach") end
    if table.find(cards, function (id) return Fk:getCardById(id).suit == Card.Spade end) then table.insertIfNeed(names, "ev__slash") end
    if table.find(cards, function (id) return Fk:getCardById(id).suit == Card.Diamond end) then table.insertIfNeed(names, "ev__jink") end
    if table.find(cards, function (id) return Fk:getCardById(id).suit == Card.Club end) then table.insertIfNeed(names, "ev__poison") end
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    local suit
    if self.interaction.data == "ev__peach" then
       suit = "heart"
    elseif self.interaction.data == "ev__slash" then
      suit = "spade"
    elseif self.interaction.data == "ev__jink" then
      suit = "diamond"
    elseif self.interaction.data == "ev__poison" then
      suit = "club"
    end
    local cards = table.filter(Self:getPile("huaniaofengyue"), function (id) return Fk:getCardById(id):getSuitString() == suit end)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
}

local xiaofengnongyue = fk.CreateTriggerSkill{
  name = "xiaofengnongyue",
  events = {fk.TurnEnd, fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.TurnEnd then
        if target == player then return end
        return #player.room.logic:getEventsOfScope(GameEvent.Damage, 1, function (e)
          local damage = e.data[1]
          if damage and player == damage.to then
            return true
          end
        end, Player.HistoryTurn) > 0 or player:getMark("xiaofengnongyue-turn") > 0
      else
        return player:hasSkill(self) and target == player and data.card.skillName == self.name
        and #table.filter(player:getPile("huaniaofengyue"), function (id) return Fk:getCardById(id).color == Card.Red end) > 0
        and #U.getUseExtraTargets(player.room, data, false) > 0
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnEnd then
      return room:askForSkillInvoke(player, self.name, nil, "#xiaofengnongyue-duel::"..target.id)
    else
      local targets = U.getUseExtraTargets(room, data, false)
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#xiaofengnongyue-choose", self.name, true)
      if #tos > 0 then
        self.cost_data = tos
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnEnd then
      room:useVirtualCard("ev__duel", nil, player, target, self.name, true)
    else
      local cards = table.filter(player:getPile("huaniaofengyue"), function (id) return Fk:getCardById(id).color == Card.Red end)
      if #cards > 0 then
        room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, "", "", true)
        table.insert(data.tos, self.cost_data)
        player.room:sendLog{
          type = "#AddTargetsBySkill",
          from = player.id,
          to = self.cost_data,
          arg = self.name,
          arg2 = data.card:toLogString(),
          toast = true,
        }
      end
    end
  end,

  refresh_events = {fk.BeforeCardsMove},
  can_refresh = function (self, event, target, player, data)
    if player:hasSkill(self) then
      for _, move in ipairs(data) do
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand and Fk:getCardById(info.cardId):getMark("@@shown-inhand") > 0 then
              return true
            end
          end
        end
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:addPlayerMark(player, "xiaofengnongyue-turn")
  end,
}

huaniaofengyue:addRelatedSkill(huaniaofengyue_trigger)
Yuuka:addSkill(huaniaofengyue)
Yuuka:addSkill(xiaofengnongyue)

Fk:loadTranslationTable{
  ["ev__yuuka"] = "风见幽香",
  ["designer:ev__yuuka"] = "KINGDOM43",
  ["illustrator:ev__yuuka"] = "荻原凛",
  ["huaniaofengyue"] = "花鸟风月",
  ["#huaniaofengyue_trigger"] = "花鸟风月",
  ["#huaniaofengyue-put"] = "你可将任意张明置手牌置于角色牌上",
  ["#huaniaofengyue-show"] = "你可明置任意张手牌",
  [":huaniaofengyue"] = "阶段技（始），你可将任意张明置手牌置于角色牌上，然后你明置任意张手牌。你可将角色牌上的所有红桃牌当【茶】，黑桃牌当【杀】，方块牌当【闪】，梅花牌当【毒】使用或打出。",
  ["xiaofengnongyue"] = "啸风弄月",
  ["#xiaofengnongyue-duel"] = "你可视为对%dest使用【决斗】",
  ["#xiaofengnongyue-choose"] = "你可为此【决斗】额外选择一个目标",
  [":xiaofengnongyue"] = "回合技（终），若你于此回合内受到过伤害或失去过明置手牌，你可视为对其使用【决斗】；当你使用此牌指定目标时，你可弃角色牌上的所有红色牌，额外选择一个目标。",
}


local weicao = General(extension, "ev__weicao", "ev", 4, 4, General.Female)

local ev__kfzx = fk.CreateTriggerSkill{
  name = "ev__kfzx",
  --mute = true,
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and data.card.type == Card.TypeTrick
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:damage({
      from = player,
      to = player,
      damage = 1,
      damageType = fk.FireDamage,
      skillName = self.name,
    })
    EV.nullifiedCard(data, data.card, player)
    local targets = AimGroup:getAllTargets(data.tos)
    table.removeOne(targets, player.id)
    if player:getLostHp() - 1 > 0 and #targets > 0 then
      local n = math.min(#targets, player:getLostHp() - 1)
      local tos = room:askForChoosePlayers(player, targets, 1, n, "#ev__kfzx-cancel:::"..data.card:toLogString(), self.name, true)
      if #tos > 0 then
        for _, id in ipairs(tos) do
          EV.nullifiedCard(data, data.card, room:getPlayerById(id))
        end
      end
    end
  end,
}

local ev__slhh = fk.CreateTriggerSkill{
  name = "ev__slhh",
  anim_type = "offensive",
  events = {fk.CardUseFinished, fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self.name) then
      if event == fk.CardUseFinished then
        return data.card.trueName == "slash" and #TargetGroup:getRealTargets(data.tos) > 0
      else
        return data.damageType == fk.FireDamage and #player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 2, function (e)
          local damage = e.data[5]
          if damage and player == damage.from and damage.damageType == fk.FireDamage then
            return true
          end
        end, Player.HistoryTurn) == 1
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      local targets = {}
      for _, id in ipairs(TargetGroup:getRealTargets(data.tos)) do
        local p = room:getPlayerById(id)
        if not player:isProhibited(p, Fk:cloneCard("blazing_flame")) and not p.dead then
          table.insertIfNeed(targets, p.id)
        end
      end
      if #targets == 0 then return false end
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#ev__slhh-target", self.name, true)
      if #to > 0 then
        self.cost_data = to[1]
        return true
      end
    else
      local to = player.room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#ev__slhh-draw", self.name, true)
      if #to > 0 then
        self.cost_data = to[1]
        return true
      end 
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      room:useVirtualCard("blazing_flame", nil, player, room:getPlayerById(self.cost_data), self.name, true)
    else
      room:getPlayerById(self.cost_data):drawCards(1, self.name)
    end
  end,
}

weicao:addSkill(ev__kfzx)
weicao:addSkill(ev__slhh)

Fk:loadTranslationTable{
  ["ev__weicao"] = "苇草",
  ["designer:ev__weicao"] = "豪曹",
  ["ev__kfzx"] = "枯法之血",
  [":ev__kfzx"] = "当你成为魔法牌的目标后，你可对自己造成1点火焰伤害，令此牌对含有你在内的至多X名角色无效（X为你已损失的体力值）。",
  ["#ev__kfzx-cancel"] = "请选择%arg无效的其他角色",
  ["ev__slhh"] = "生灵火花",
  [":ev__slhh"] = "当你使用的【杀】结算结束后，你可视为对其中一个目标使用【炽焰】。当你于一回合内首次造成火焰伤害后，你可令一名角色摸一张牌。",
  ["#ev__slhh-target"] = "生灵火花：请选择【炽焰】的目标",
  ["#ev__slhh-draw"] = "生灵火花：你可令一名角色摸一张牌",

  ["$ev__kfzx1"] = "战火，会烧尽荒野。",
  ["$ev__kfzx2"] = "我的火，很烫。",
  ["$ev__slhh1"] = "活着的火焰会净化你们污浊的内在。",
  ["$ev__slhh2"] = "我，就是深池！",
  ["~ev__weicao"] = "不，我不会让任何人伤害你，绝不会。",
}

local chitong = General(extension, "ev__chitong", "ev", 4, 4, General.Female)
local zhouduzhiren = fk.CreateTriggerSkill{
  name = "zhouduzhiren",
  events = {fk.EventPhaseStart, fk.CardEffecting},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return target == player and player:hasSkill(self) and player.phase == Player.Play
    elseif event == fk.CardEffecting then
      return player:hasSkill(self) and player:getMark("@@zhouduzhiren-turn") > 0
      and player.id == data.from and (data.card.trueName == "slash" or data.card.trueName == "poison")
      and player.room:getPlayerById(data.to).hp == 1
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return player.room:askForSkillInvoke(player, self.name)
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:loseHp(player, 1, self.name)
      if not player.dead then
        room:addPlayerMark(player, "@@zhouduzhiren-turn")
      end
    else
      room:killPlayer({who = data.to,})
    end
  end,
}

local zhouduzhiren_attackrange = fk.CreateAttackRangeSkill{
  name = "#zhouduzhiren_attackrange",
  correct_func = function (self, from, to)
    if from:hasSkill("zhouduzhiren") and from:getMark("@@zhouduzhiren-turn") > 0 then
      return 1
    end
  end,
}

local zhouduzhiren_slash = fk.CreateTargetModSkill{
  name = "#zhouduzhiren_targetmod",
  residue_func = function(self, player, skill, scope, card)
    if player:hasSkill("zhouduzhiren") and skill.trueName == "slash_skill" and scope == Player.HistoryPhase and player:getMark("@@zhouduzhiren-turn") > 0 then
      return 1
    end
  end,
}

local meishikuangre = fk.CreateTriggerSkill{
  name = "meishikuangre",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self.name) then
      return #player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
        if e.data[1] == player and e.data[2] < 0 then
          return true
        end
      end, Player.HistoryTurn) > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = player:getLostHp()
    player:drawCards(n, self.name)
    if n - 1 > 0 then
      n = n - 1
      local cards = room:askForCard(player, n, n, true, self.name, false, ".", "#meishikuangre:::"..n)
      room:useVirtualCard("banquet", cards, player, room.alive_players, self.name, true)
    end
  end,
}

zhouduzhiren:addRelatedSkill(zhouduzhiren_attackrange)
zhouduzhiren:addRelatedSkill(zhouduzhiren_slash)
chitong:addSkill(zhouduzhiren)
chitong:addSkill(meishikuangre)

Fk:loadTranslationTable{
  ["ev__chitong"] = "赤瞳",
  ["designer:ev__chitong"] = "Rubace",
  ["illustrator:ev__chitong"] = "洋步",
  ["zhouduzhiren"] = "咒毒之刃",
  [":zhouduzhiren"] = "阶段技（始），你可失去1点体力，于本回合内获得以下效果：你使用【杀】的次数上限与你的攻击范围均+1；当你使用的【杀】或【毒】对体力值为1的目标角色生效时，其死亡",
  ["@@zhouduzhiren-turn"] = "咒毒之刃",
  ["meishikuangre"] = "美食狂热",
  [":meishikuangre"] = "回合技（终），若你于此回合内扣减过体力，你可摸X张牌，然后你将X-1张牌当【欢饮酒宴】使用（X为你已损失的体力值）。",
  ["#meishikuangre"] = "请选择%arg张牌当【欢饮酒宴】使用",
}


local Kled_Skaarl = General(extension, "ev__kled_skaarl", "ev", 4)
local Kled = General(extension, "ev__kled", "ev", 2)
Kled_Skaarl.reverse = "ev__kled"
Kled.reverse = "ev__kled_skaarl"
Kled.hidden = true

local ev__feisuo = fk.CreateTriggerSkill{
  name = "ev__feisuo",
  anim_type = "offensive",
  events ={fk.EventPhaseStart, fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return target == player and player:hasSkill(self) and player.phase == Player.Finish
    else
      return player:hasSkill(self) and table.contains(U.getMark(player, "ev__feisuo"), target.id)
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      local targets = table.map(table.filter(player.room:getOtherPlayers(player), function(p) return player:inMyAttackRange(p) end), Util.IdMapper)
      local tos, cards = player.room:askForChooseCardsAndPlayers(player, 1, 1, targets, 1, 1, ".|.|.|.|.|basic", "#ev__feisuo-give", self.name, true, true)
      if #tos > 0 and #cards > 0 then
        self.cost_data = {tos[1], cards[1]}
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local to = room:getPlayerById(self.cost_data[1])
      room:moveCardTo(self.cost_data[2], Player.Hand, to, fk.ReasonGive, self.name, nil, false, player.id)
      local mark = U.getMark(player, "ev__feisuo")
      table.insertIfNeed(mark, self.cost_data[1])
      room:setPlayerMark(player, "ev__feisuo", mark)
      room:setPlayerMark(to, "ev__feisuo_mark", self.cost_data[2])
    else
      local mark = U.getMark(player, "ev__feisuo")
      table.removeOne(mark, target.id)
      room:setPlayerMark(player, "ev__feisuo", mark)
      room:damage({
        from = player,
        to = target,
        damage = 1,
        damageType = fk.NormalDamage,
        skillName = self.name,
      })
      if not target.dead then
        local suit = Fk:getCardById(target:getMark("ev__feisuo_mark")):getSuitString()
        room:setPlayerMark(target, "ev__feisuo_mark", 0)
        local choice = room:askForChoice(target, {"ev__feisuo1:::"..suit, "ev__feisuo2"}, self.name)
        if choice == "ev__feisuo2" then
          room:addPlayerMark(target, "ev__feisuo-turn")
        else
          local cards = table.filter(target:getCardIds("he"), function(id) return Fk:getCardById(id):getSuitString() == suit end)
          if #cards > 0 then
            room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, target.id)
          end
        end
      end
    end
  end,
}

local feisuo_prohibit = fk.CreateProhibitSkill{
  name = "#ev__feisuo_prohibit",
  is_prohibited = function(self, from, to, card)
    return from:getMark("ev__feisuo-turn") > 0 and from == to
  end,
}

local ev__goback = fk.CreateTriggerSkill{
  name = "ev__goback",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.EnterDying, fk.BeforeTurnOver},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name) and player == target
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EnterDying then
      local n = 2 - player.hp
      room:recover({
        who = player,
        num = n,
        recoverBy = player,
        skillName = self.name
      })
      room:addPlayerMark(player, "ev__goback-turn")
      room:notifySkillInvoked(player, self.name)
      player:turnOver()
    else
      local duputy = player.deputyGeneral == "ev__kled_skaarl"
      EV.changeHero(player, "ev__kled", duputy)
      return true
    end
  end,
}

local goback_prohibit = fk.CreateProhibitSkill{
  name = "#ev__goback_prohibit",
  is_prohibited = function(self, from, to, card)
    return to:getMark("ev__goback-turn") > 0
  end,
}

ev__feisuo:addRelatedSkill(feisuo_prohibit)
ev__goback:addRelatedSkill(goback_prohibit)
Kled_Skaarl:addSkill(ev__feisuo)
Kled_Skaarl:addSkill(ev__goback)

local ev__baolie = fk.CreateTriggerSkill{
  name = "ev__baolie",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.CardUsing, fk.Damage, fk.BeforeTurnOver},
  derived_piles = {"ev__baolie"},
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardUsing then
      return data.card.trueName == "slash" and target == player and player:hasSkill(self)
    else
      return target == player and player:hasSkill(self)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing or event == fk.Damage then
      room:notifySkillInvoked(player, self.name)
      player:drawCards(1, self.name)
      if player:isKongcheng() then return end
      local card = room:askForCard(player, 1, 1, false, self.name, false, ".", "#ev__baolie-card")
      player:addToPile("ev__baolie", card, true, self.name)
      if #player:getPile("ev__baolie") >= 4 then
        --room:moveCardTo(player:getPile("ev__baolie"), Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, "", true)
        local n = 2 - player.hp
        room:recover({
          who = player,
          num = n,
          recoverBy = player,
          skillName = self.name
        })
        player:turnOver()
      end
    else
      local duputy = player.deputyGeneral == "ev__kled"
      EV.changeHero(player, "ev__kled_skaarl", duputy)
      return true
    end
  end,
}

local baolie_attackrange = fk.CreateAttackRangeSkill{
  name = "#ev__baolie_attackrange",
  correct_func = function (self, from, to)
    if from:hasSkill("ev__baolie") then
      return 1
    end
  end,
}

local ev__baolie_tar = fk.CreateTargetModSkill{
  name = "#ev__baolie_targetmod",
  residue_func = function(self, player, skill, scope, card)
    if player:hasSkill("ev__baolie") and skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
      return 999
    end
  end,
}

ev__baolie:addRelatedSkill(baolie_attackrange)
ev__baolie:addRelatedSkill(ev__baolie_tar)

Kled:addSkill(ev__baolie)

Fk:loadTranslationTable{
  ["ev__kled_skaarl"] = "克烈斯嘎尔",
  ["designer:ev__kled_skaarl"] = "豪曹",
  ["ev__kled"] = "克烈",
  ["designer:ev__kled"] = "豪曹",
  ["ev__feisuo"] = "飞索捕熊器",
  ["#ev__feisuo_prohibit"] = "飞索",
  [":ev__feisuo"] = "结束阶段，你可将一张基础牌交给你攻击范围内的一名角色；其下回合开始时，你对其造成1点伤害，然后其选择一项：1.弃置所有与此牌花色相同的牌；2.其于此回合内不是其使用牌的合法目标。",
  ["#ev__feisuo-give"] = "你可将一张基础牌交给你攻击范围内的一名角色",
  ["ev__feisuo1"] = "弃置所有%arg牌",
  ["ev__feisuo2"] = "此回合不能使用牌指定自己为目标",
  ["ev__goback"] = "回来，懦夫！",
  [":ev__goback"] = "锁定技，当你进入濒死状态时，你将体力回复至2点，然后你翻面，且你于当前回合内不是牌的合法目标。",
  ["#ev__goback_prohibit"] = "懦夫",
  ["ev__baolie"] = "暴烈秉性",
  [":ev__baolie"] = "锁定技，你的攻击范围+1，你使用【杀】无次数限制。当你使用【杀】时或造成伤害后，你摸一张牌，将一张牌置于角色牌上；然后若你的角色牌上有四张牌，你将这些牌置入弃牌堆，将体力回复至2点，翻面。",
  ["#ev__baolie-card"] = "暴烈秉性：请将一张牌置于角色牌上",
}

local ali = General(extension, "ev__ali", "ev", 3, 3, General.Female)

local shehunduopo = fk.CreateTriggerSkill{
  name = "shehunduopo",
  frequency = Skill.Compulsory,
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card and data.card.trueName == "slash" and not data.to.dead
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local all_choices = {"shehunduopo1:"..player.id..":"..data.to.id, "shehunduopo2:"..player.id}
    local choices = {}
    if not data.to:isNude() then table.insert(choices, all_choices[1]) end
    if player:isWounded() then table.insert(choices, all_choices[2]) end
    if #choices == 0 then return end
    local chooser = player
    if player:distanceTo(data.to) ~= 1 then
      chooser = data.to
    end
    local choice = room:askForChoice(chooser, choices, self.name, "", false, all_choices)
    if string.find(choice, "shehunduopo1") then
      local id = EV.askForCardChosen(room, player, data.to, "hes", self.name)
      if id > 0 then
        room:moveCardTo(id, Card.PlayerHand, player, fk.ReasonPrey, self.name, "", true, player.id)
      end
    else
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
  end,
}

local meihuoyaoshu = fk.CreateActiveSkill{
  name = "meihuoyaoshu",
  anim_type = "control",
  prompt = "你可用一张红桃牌替换一名其他角色的一张牌",
  target_num = 1,
  card_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return Fk:getCardById(to_select).suit == Card.Heart
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and Self.id ~= to_select and not Fk:currentRoom():getPlayerById(to_select):isNude()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local id = EV.askForCardChosen(room, player, target, "hes", self.name)
    --local id = room:askForCardChosen(player, target, "he", self.name)
    if id > 0 then
      --room:moveCardTo(effect.cards[1], Card.PlayerHand, target, fk.ReasonJustMove, self.name, "", true, player.id)
      --room:moveCardTo(id, Card.PlayerHand, player, fk.ReasonJustMove, self.name, "", true, player.id)
      U.swapCards(room, player, player, target, {effect.cards[1]}, {id}, self.name)
      local mark = U.getMark(player, "meihuoyaoshu")
      table.insertIfNeed(mark, target.id)
      room:addPlayerMark(target, "@@meihuoyaoshu-buff")
      room:setPlayerMark(player, "meihuoyaoshu", mark)
    end
  end,
}

local meihuoyaoshu_trigger = fk.CreateTriggerSkill{
  name = "#meihuoyaoshu_trigger",
  mute = true,
  events = {fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card and data.card.suit == Card.Heart and data.card.type ~= Card.TypeEquip
    and #U.getMark(player, "meihuoyaoshu") ~= 0 and table.contains(U.getMark(player, "meihuoyaoshu"), target.id)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#meihuoyaoshu-ask::"..target.id..":"..data.card:toLogString())
  end,
  on_use = function(self, event, target, player, data)
    player.room:notifySkillInvoked(player, "meihuoyaoshu", "control")
    data.tos = {}
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill("meihuoyaoshu", true, true) then
      return #U.getMark(player, "meihuoyaoshu") ~= 0 and table.contains(U.getMark(player, "meihuoyaoshu"), target.id)
      or target:getMark("@@meihuoyaoshu-buff") > 0
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local mark = U.getMark(player, "meihuoyaoshu")
    table.removeOne(mark, target.id)
    player.room:setPlayerMark(target, "@@meihuoyaoshu-buff", 0)
    player.room:setPlayerMark(player, "meihuoyaoshu", mark)
  end,
}

local meihuoyaoshu_distance = fk.CreateDistanceSkill{
  name = "#meihuoyaoshu_distance",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    if from:hasSkill("meihuoyaoshu") and to:getMark("@@meihuoyaoshu-buff") > 0 then
      return 0 - to:getMark("@@meihuoyaoshu-buff")
    end
  end,
}

local linghuntuxi = fk.CreateViewAsSkill{
  name = "linghuntuxi",
  pattern = "nullification,jink",
  interaction = function()
    local names = {}
    for _, name in ipairs({"ev__jink","ev__nullification"}) do
      local card = Fk:cloneCard(name)
      if (Fk.currentResponsePattern == nil and Self:canUse(card)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card)) then
        table.insertIfNeed(names, card.name)
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names}
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if #cards ~= 0 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  after_use = function (self, player)
    player.room:addPlayerMark(player, "@linghuntuxi")
  end,

  enabled_at_play = Util.FalseFunc,
  enabled_at_response = function(self, player, response)
    return player:usedSkillTimes(self.name, Player.HistoryGame) < 3 and player:getMark("soul_buff") > 0 and not response
  end,
}

local soul_buff = fk.CreateTriggerSkill{
  name = "#soul_buff",
  events = {fk.TurnEnd},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player:usedSkillTimes("linghuntuxi", Player.HistoryTurn) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local success, dat = room:askForUseActiveSkill(player, "soul_viewas", "#soul-slash", true)
    if success then
      self.cost_data = dat
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, "linghuntuxi", "offensive")
    local card = Fk.skills["soul_viewas"]:viewAs(self.cost_data.cards)
    room:useCard{
      from = player.id,
      tos = table.map(self.cost_data.targets, function(id) return {id} end),
      card = card,
      extraUse = true,
    }
  end,

  refresh_events = {fk.PreCardEffect, fk.AfterCardUseDeclared},
  can_refresh = function(self, event, target, player, data)
    if event == fk.PreCardEffect then
      return player:hasSkill(self) and (data.card.trueName == "slash" or data.card.type == Card.TypeTrick)
    else
      return player:hasSkill(self) and target == player and data.card.skillName == "linghuntuxi"
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.PreCardEffect then
      if player.id == data.to then
        room:addPlayerMark(player, "soul_buff")
      else
        room:setPlayerMark(player, "soul_buff", 0)
      end
    elseif event == fk.AfterCardUseDeclared then--清理无效标记
      room:setPlayerMark(player, "soul_buff", 0)
    end
  end,
}

local soul_viewas = fk.CreateViewAsSkill{
  name = "soul_viewas",
  pattern = "slash",
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("slash")
    card.skillName = "linghuntuxi"
    card:addSubcards(cards)
    return card
  end,
}

Fk:addSkill(soul_viewas)
linghuntuxi:addRelatedSkill(soul_buff)
meihuoyaoshu:addRelatedSkill(meihuoyaoshu_trigger)
meihuoyaoshu:addRelatedSkill(meihuoyaoshu_distance)
ali:addSkill(shehunduopo)
ali:addSkill(meihuoyaoshu)
ali:addSkill(linghuntuxi)

Fk:loadTranslationTable{
  ["ev__ali"] = "阿狸",
  ["designer:ev__ali"] = "zengyouyu",
  ["shehunduopo"] = "摄魂夺魄",
  [":shehunduopo"] = "锁定技，当你使用【杀】造成伤害后，若你与受伤角色的距离为1/不为1，你/其选择一项：1.令你获得其一张牌；2.令已受伤的你回复1点体力。",
  ["shehunduopo1"] = "令%src获得%dest一张牌",
  ["shehunduopo2"] = "令已受伤的%src回复1点体力",
  ["meihuoyaoshu"] = "魅惑妖术",
  [":meihuoyaoshu"] = "阶段技，你可用一张红桃牌替换一名其他角色的一张牌，然后直至其下回合开始：你与其的距离-1；其使用红桃非装备牌指定目标后，你可令此牌无效。",
  ["#meihuoyaoshu_trigger"] = "魅惑妖术",
  ["@@meihuoyaoshu-buff"] = "魅惑妖术",
  ["#meihuoyaoshu-ask"] = "你可令%dest使用的%arg无效",
  ["linghuntuxi"] = "灵魂突袭",
  [":linghuntuxi"] = "每局限三次，你可视为使用【闪】或【魔法禁令】抵消对你生效前的牌；一名角色的回合结束时，若你于此回合内以此法使用过牌，你可将一张牌当【杀】使用。",
  ["#soul_buff"] = "灵魂突袭",
  ["@linghuntuxi"] = "灵魂突袭",
  ["#soul-slash"] = "你可将一张牌当【杀】使用",
}

local Tetris = General(extension, "ev__tetris", "ev", 4, 4, General.Agender)
local sichongfangkuai = fk.CreateTriggerSkill{
  name = "sichongfangkuai",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    data.n = data.n + 2
  end,

  refresh_events = {fk.AfterDrawNCards},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local unshown = table.filter(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getMark("@@shown-inhand") == 0 end)
    local n = math.min(#unshown, 4)
    local cards = player.room:askForCard(player, n, n, false, self.name, false, tostring(Exppattern{ id = unshown }), "#sichongfangkuai-show")
    EV.OpenCards(player.room, player, cards, self.name)
  end
}

local sichongfangkuai_effect = fk.CreateProhibitSkill{
  name = "#sichongfangkuai_effect",
  prohibit_use = function(self, player, card)
    if player:hasSkill(self) and table.find(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getMark("@@shown-inhand") > 0 end)
    and Fk:currentRoom():getCardArea(card) == Card.PlayerHand then
      if card:isVirtual() then
        return table.find(card.subcards, function (id) return Fk:getCardById(id):getMark("@@shown-inhand") == 0 end)
      else
        return card:getMark("@@shown-inhand") == 0
      end
    end
  end,
}

local fangkuaileiji = fk.CreateTriggerSkill{
  name = "fangkuaileiji",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseEnd} ,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player and player.phase == Player.Discard then
      local turn_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Phase, true)
      local end_id = turn_event.id
      return #U.getEventsByRule(player.room, GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.from and move.from == player.id and move.moveReason == fk.ReasonDiscard then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand then
                return true
              end
            end
          end
        end
        return false
      end, end_id) > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:killPlayer({who = player.id,})
  end,
}
local fangkuaileiji_maxcards = fk.CreateMaxCardsSkill{
  name = "#fangkuaileiji_maxcards",
  fixed_func = function (self, player)
    if player:hasSkill("fangkuaileiji") then
      return player.hp * 2
    end
  end,
}

sichongfangkuai:addRelatedSkill(sichongfangkuai_effect)
fangkuaileiji:addRelatedSkill(fangkuaileiji_maxcards)
Tetris:addSkill(sichongfangkuai)
Tetris:addSkill(fangkuaileiji)

Fk:loadTranslationTable{
  ["ev__tetris"] = "俄罗斯方块",
  ["designer:ev__tetris"] = "洛清",
  ["sichongfangkuai"] = "四重方块",
  ["#sichongfangkuai_effect"] = "四重方块",
  ["#sichongfangkuai-show"] = "请明置四张手牌",
  [":sichongfangkuai"] = "锁定技，摸牌阶段，你额外摸两张牌，然后明置四张手牌。若你有明置手牌，你不能使用暗置手牌。",
  ["fangkuaileiji"] = "方块累积",
  [":fangkuaileiji"] = "锁定技，你的手牌上限为体力值的两倍，弃牌阶段结束时，如果你于本阶段内弃置过手牌，你死亡。",
}

local Bagpipe = General(extension, "ev__bagpipe", "ev", 4, 4, General.Female)

local army_tradition = fk.CreateTriggerSkill{
  name = "army_tradition",
  events = {fk.TurnEnd},
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      return target:getMark("army_tradition-turn") > 0 and #player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        return e.data[1].card.trueName == "slash" and e.data[1].from == target.id
      end, Player.HistoryTurn) > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(target, {"ev__wusasi1", "army_tradition1"}, self.name)
    if choice == "ev__wusasi1" then
      target:drawCards(1, self.name)
    elseif choice == "army_tradition1" then
      target:gainAnExtraPhase(Player.Play, true)
    end
  end,

  refresh_events = {"fk.RoleShown"},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and data.from == target.id
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addPlayerMark(target, "army_tradition-turn")
  end
}

local efficient_dash = fk.CreateViewAsSkill{
  name = "efficient_dash",
  prompt = "#efficient_dash",
  pattern = "slash",
  interaction = function()
    local names = {}
    if #table.filter(Self.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeTrick end) > 0 then
      table.insert(names, "trickcard")
    end
    if #table.filter(Self.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeEquip end) > 0 then
      table.insert(names, "equipcard")
    end
    if #names == 0 then return end
    return UI.ComboBox { choices = names }
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return nil end
    local trick = table.filter(Self.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeTrick end)
    local equip = table.filter(Self.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeEquip end)
    local card = Fk:cloneCard("ev__slash")
    if self.interaction.data == "trickcard" then
      card:addSubcards(trick)
    else
      card:addSubcards(equip)
    end
    card.skillName = self.name
    return card
  end,
  after_use = function(self, player, use)
    player:addCardUseHistory("slash", -1)
  end,
  enabled_at_play = function(self, player)
    return not player:isKongcheng() and
      (#table.filter(player.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeTrick end) > 0
      or #table.filter(player.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeEquip end) > 0)
  end,
  enabled_at_response = function(self, player, response)
    return not response and
      (#table.filter(player.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeTrick end) > 0
      or #table.filter(player.player_cards[Player.Hand], function(id) return Fk:getCardById(id).type == Card.TypeEquip end) > 0)
  end,
}

local dash_trigger = fk.CreateTriggerSkill{
  name = "#efficient_dash_trigger",
  mute = true,
  events = {fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash"-- and #U.getUseExtraTargets(player.room, data, false) > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".",
    }
    room:judge(judge)
    if judge.card.suit == data.card.suit  then
      local tos = room:askForChoosePlayers(player, U.getUseExtraTargets(room, data, false), 1, 1, "#efficient_dash-choose", self.name, true)
      if #tos > 0 then
        table.insert(data.tos, tos )
        player:broadcastSkillInvoke("efficient_dash")
        room:sendLog{
          type = "#AddTargetsBySkill",
          from = player.id,
          to = self.cost_data,
          arg = self.name,
          arg2 = data.card:toLogString(),
          toast = true,
        }
      end
    end
  end,
}
efficient_dash:addRelatedSkill(dash_trigger)
Bagpipe:addSkill(army_tradition)
Bagpipe:addSkill(efficient_dash)

Fk:loadTranslationTable{
  ["ev__bagpipe"] = "风笛",
  ["designer:ev__bagpipe"] = "小樱",
  ["army_tradition"] = "军事传统",
  [":army_tradition"] = "回合技（终），若其于此回合内明置过身份牌且使用过【杀】，你可令其选择一项：1.摸一张牌；2.于此阶段结束后获得一个额外的出牌阶段。",
  ["efficient_dash"] = "高效冲击",
  ["#efficient_dash_trigger"] = "高效冲击",
  [":efficient_dash"] = "你可将手牌中的所有装备牌或魔法牌当不计入次数限制的【杀】使用。当你使用【杀】指定目标时，你可判定，若结果与此【杀】花色相同，则你可额外选择一个目标。",
  ["army_tradition1"] = "额外出牌阶段",
  ["trickcard"] = "魔法牌",
  ["equipcard"] = "装备牌",
  ["#efficient_dash"] = "你可选择类别和【杀】的目标角色",
  ["#efficient_dash-choose"] = "请选择此【杀】的一个额外目标",

  ["$army_tradition1"] = "战术使人思维明晰！",
  ["$army_tradition2"] = "纪律使人意志坚定！",
  ["$efficient_dash1"] = "进攻！",
  ["$efficient_dash2"] = "我和我的破城矛，来自维多利亚！",
  ["~ev__bagpipe"] = "你先走！",
}

local Nian = General(extension, "ev__nian", "ev", 4, 4, General.Female)

local jijiachengshan = fk.CreateTriggerSkill{
  name = "jijiachengshan",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:usedSkillTimes(self.name) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local suits = {}
    local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
      local use = e.data[1]
      if use.from == player.id then
        table.insertIfNeed(suits, use.card:getSuitString())
      end
    end, Player.HistoryGame)
    local n = #suits + 1
    local ids = room:getNCards(n)
    local equips = table.filter(ids, function (id) return Fk:getCardById(id).type == Card.TypeEquip end)
    local cards, _ = U.askforChooseCardsAndChoice(player, equips, {"OK"}, self.name, "#jijiachengshan-choose", {"Cancel"}, 1, 999, ids)
    if #cards > 0 then
      room:setPlayerMark(player, "jijiachengshan", cards)
      U.askForDistribution(player, cards, room:getAlivePlayers(), self.name, #cards, #cards, "#jijiachengshan", player:getMark("jijiachengshan"))
      room:setPlayerMark(player, "jijiachengshan", 0)
      for _, id in ipairs(cards) do
        table.removeOne(ids, id)
      end
    end
    for i = n, 1, -1 do
      table.insert(room.draw_pile, 1, ids[i])
    end
  end,
}

local ev__tongyin = fk.CreateTriggerSkill{
  name = "ev__tongyin",
  events = {fk.BeforeCardsMove, fk.DamageInflicted},
  frequency = Skill.Compulsory,
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or #player:getCardIds(Player.Equip) == 0 then return false end
    if event == fk.BeforeCardsMove then
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.proposer ~= player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    else
      if target == player and data.card and data.card.trueName == "slash" then
        return table.find(player:getCardIds(Player.Equip), function (id) return Fk:getCardById(id).color == data.card.color end)
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.BeforeCardsMove then
      local ids = {}
      for _, move in ipairs(data) do
        if move.from == player.id and move.proposer ~= player.id
        and (move.moveReason == fk.ReasonDiscard or move.moveReason == fk.ReasonPrey)then
          local move_info = {}
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            if info.fromArea == Card.PlayerEquip then
              table.insert(ids, id)
            else
              table.insert(move_info, info)
            end
          end
          if #ids > 0 then
            move.moveInfo = move_info
          end
        end
      end
      if #ids > 0 then
        player.room:sendLog{
          type = "#cancelDismantle",
          card = ids,
          arg = self.name,
        }
      end
    else
      data.damage = data.damage - 1
    end
  end,
}

local ev__tongyins = fk.CreateTriggerSkill{
  name = "ev__tongyin&",
  events = {fk.BeforeCardsMove, fk.DamageInflicted},
  frequency = Skill.Compulsory,
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or #player:getCardIds(Player.Equip) == 0 then return false end
    if event == fk.BeforeCardsMove then
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.proposer ~= player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    else
      if target == player and data.card and data.card.trueName == "slash" then
        return table.find(player:getCardIds(Player.Equip), function (id) return Fk:getCardById(id).color == data.card.color end)
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.BeforeCardsMove then
      local ids = {}
      for _, move in ipairs(data) do
        if move.from == player.id and move.proposer ~= player.id
        and (move.moveReason == fk.ReasonDiscard or move.moveReason == fk.ReasonPrey)then
          local move_info = {}
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            if info.fromArea == Card.PlayerEquip then
              table.insert(ids, id)
            else
              table.insert(move_info, info)
            end
          end
          if #ids > 0 then
            move.moveInfo = move_info
          end
        end
      end
      if #ids > 0 then
        player.room:sendLog{
          type = "#cancelDismantle",
          card = ids,
          arg = self.name,
        }
      end
    else
      data.damage = data.damage - 1
    end
  end,
}

local ev__tieyu = fk.CreateTriggerSkill{
  name = "ev__tieyu",
  anim_type = "drawcard",
  frequency = Skill.Limited,
  events ={fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
    and #player:getCardIds(Player.Equip) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return not p:hasSkill("ev__tongyin") end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 999, "#ev__tieyu-choose", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player, "tieyu-used")
    room:moveCardTo(player:getCardIds(Player.Equip), Card.PlayerHand, player, fk.ReasonJustMove, self.name, "", true)
    local players = table.map(self.cost_data, Util.Id2PlayerMapper)
    for _, p in ipairs(players) do
      room:handleAddLoseSkills(p, "ev__tongyin&")
    end
  end,

  refresh_events = {fk.AfterDrawPileShuffle, fk.TurnStart, fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterDrawPileShuffle then
      return player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryGame) > 0
    else
      return target == player and player:hasSkill(self.name, true, true) and (player:getMark("tieyu-used") > 0 or event == fk.Deathed)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.AfterDrawPileShuffle then
      player.room:changeMaxHp(player, -1)
      player:setSkillUseHistory(self.name, 0, Player.HistoryGame)
    else
      for _, p in ipairs(player.room:getOtherPlayers(player)) do
        if p:hasSkill("ev__tongyin&") then
          player.room:handleAddLoseSkills(p, "-ev__tongyin&")
        end
      end
    end
  end,
}

Fk:addSkill(ev__tongyins)
Nian:addSkill(jijiachengshan)
Nian:addSkill(ev__tongyin)
Nian:addSkill(ev__tieyu)

Fk:loadTranslationTable{
  ["ev__nian"] = "年",
  ["designer:ev__nian"] = "KINGDOM43",
  ["jijiachengshan"] = "积甲成山",
  [":jijiachengshan"] = "回合技，当你使用牌时，你可观看牌堆顶的X张牌，将其中的任意张装备牌交给任意名角色（X为你使用过的牌的花色数+1）。",
  ["#jijiachengshan-choose"] = "积甲成山：请选择其中的任意张装备牌",
  ["#jijiachengshan"] = "请分配这些装备牌",
  ["ev__tongyin"] = "铜印",
  [":ev__tongyin"] = "锁定技，你装备区里的牌不能被其他角色弃置或获得。当你受到【杀】造成的伤害时，若此【杀】与你装备区里的牌颜色相同，则你令此伤害-1。",
  ["ev__tongyin&"] = "铜印",
  [":ev__tongyin&"] = "锁定技，你装备区里的牌不能被其他角色弃置或获得。当你受到【杀】造成的伤害时，若此【杀】与你装备区里的牌颜色相同，则你令此伤害-1。",
  ["ev__tieyu"] = "铁御",
  [":ev__tieyu"] = "限定技，结束阶段，你可获得装备区里的所有牌，令任意名角色获得“铜印”直至你的下回合开始。当牌堆洗切时，你可减少1点体力上限，重置此技能。",
  ["#ev__tieyu-choose"] = "你可以令任意名角色获得“铜印”直至你的下回合开始",

  ["$jijiachengshan1"] = "打造武器的工匠，必须承担它们带来的血腥。",
  ["$jijiachengshan2"] = "铸乃众相之柱。",
  ["$ev__tongyin1"] = "生杀之机，焉能拱手相让？",
  ["$ev__tongyin2"] = "明王圣帝，谁能去兵哉？",
  ["$ev__tongyin&1"] = "生杀之机，焉能拱手相让？",
  ["$ev__tongyin&2"] = "明王圣帝，谁能去兵哉？",
  ["$ev__tieyu1"] = "哦？要我亲自动手吗？",
  ["$ev__tieyu2"] = "我为什么要在你们这些低劣造物上浪费时间？",
  ["~ev__nian"] = "欸，不要啦。",
}

local Steve = General(extension, "ev__steve", "ev", 4)

local ev__caikuang = fk.CreateTriggerSkill{
  name = "ev__caikuang",
  --priority = 1.1,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.extra_data and data.extra_data.caikuang
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#ev__caikuang-throw")
  end,
  on_use = function(self, event, target, player, data)
    player.room:setCardMark(data.card, "ev__caikuang-buff", 0)
    local id = player.room:getNCards(1, "bottom")
    player.room:moveCardTo(id, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, "", "", true)
  end,

  refresh_events = {fk.AfterCardsMove, fk.PreCardUse},
	can_refresh = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.AfterCardsMove then
        for _, move in ipairs(data) do
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.DrawPile or move.toArea == Card.DrawPile then
              return true
            end
          end
        end
      else
        if target == player and data.card:isVirtual() then
          return table.find(data.card.subcards, function (id) return player:getMark("ev__caikuang") == id end)
        end
      end
    end
	end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      local n = #player.room.draw_pile
      local ids = {player.room.draw_pile[n], player.room.draw_pile[n-1]}
      --room:setPlayerMark(player, "@[private]$caikuang", ids)
      U.setPrivateMark(player, "$caikuang", ids)
      room:setPlayerMark(player, "ev__caikuang", ids[1])
    else
      room:addPlayerMark(player, "caikuang-turn")
      data.extra_data = data.extra_data or {}
      data.extra_data.caikuang = data.card.id
    end
  end,
}

Steve:addSkill(ev__caikuang)

local hecheng_rules = function(pattern)
  local suits = {}
  local hplost = table.filter(U.getAllCardNames("bt"), function(name) return Fk:cloneCard(name).is_damage_card or name == "ev__poison" end)
  local tricks = U.getAllCardNames("t")
  local hprecover = {"ev__peach", "holy_blessing", "ev__god_salvation", "armistices"}
  local notsingle = table.filter(U.getAllCardNames("bt"), function(name)
    return name == "ev__jink" or name == "ev__peach" or name == "ev__nullification" or name == "midas_touch" 
    or not EV.isSingleTarget(Fk:cloneCard(name)) end)
  if table.contains(hplost, pattern) then
    table.insert(suits, "spade")
  end
  if table.contains(tricks, pattern) then
    table.insert(suits, "club")
  end
  if table.contains(hprecover, pattern) then
    table.insert(suits, "heart")
  end
  if table.contains(notsingle, pattern) then
    table.insert(suits, "diamond")
  end
  return suits
end

local ev__hecheng = fk.CreateViewAsSkill{
  name = "ev__hecheng",
  pattern = ".",
  expand_pile = function()
    if Self:getMark("caikuang-turn") == 0 and Self:getMark("ev__caikuang") ~= 0 then
      return {Self:getMark("ev__caikuang")}
    end
  end,
  interaction = function()
    local all_names = U.getAllCardNames("bt")
    return U.CardNameBox { choices = all_names }
  end,
  card_filter = function(self, to_select, selected)
    --if Fk:currentRoom():getCardArea(to_select) == Player.Equip then return end
    local suits = hecheng_rules(self.interaction.data)
    for _, id in ipairs(selected) do
      table.removeOne(suits, Fk:getCardById(id):getSuitString())
    end
    if #suits == 0 then
      return true
    elseif #suits == 1 then
      return Fk:getCardById(to_select):getSuitString() == suits[1]
    else
      return table.contains(suits, Fk:getCardById(to_select):getSuitString())
    end
  end,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local suits = hecheng_rules(self.interaction.data)
    for _, id in ipairs(cards) do
      table.removeOne(suits, Fk:getCardById(id):getSuitString())
    end
    if #suits ~= 0 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
}

Steve:addSkill(ev__hecheng)

Fk:loadTranslationTable{
  ["ev__steve"] = "史蒂夫",
  ["designer:ev__steve"] = "洛清",
  ["ev__caikuang"] = "采矿",
  ["@[private]$caikuang"] = "采矿",
  [":ev__caikuang"] = "回合技，你可将牌堆底的一张牌用于以转化的方式使用或打出牌，然后你可将牌堆底的一张牌置入弃牌堆。牌堆底的两张牌对你可见。",
  ["#ev__caikuang-throw"] = "你可将牌堆底的一张牌置入弃牌堆",
  ["ev__hecheng"] = "合成",
  [":ev__hecheng"] = "你可将至少两张牌当任意基础牌或即时魔法牌使用或打出，且需含有："..
  "<br />♠~若此牌为可扣减体力的牌；"..
  "<br />♣~若此牌为魔法牌；"..
  "<br />♥~若此牌为可回复体力的牌；"..
  "<br />♦~若此牌的目标不为唯一其他角色。",
}

local Skadi = General(extension, "ev__skadi", "ev", 4, 4, General.Female)
local ev__yuelang = fk.CreateTriggerSkill{
  name = "ev__yuelang",
  anim_type = "offensive",
  events = {fk.DamageCaused, fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if event == fk.DamageCaused then
      if target == player and player:hasSkill(self.name) then
        if player:usedSkillTimes("ev__yongchao", Player.HistoryGame) > 0 then
          return true
        else
          return #player.room.logic:getEventsOfScope(GameEvent.Damage, 2, function (e)
            local damage = e.data[1]
            if damage and damage.from and player == damage.from then
              return true
            end
          end, Player.HistoryTurn) == 1
        end
      end
    else
      if player:hasSkill(self.name) and data.damage > 1 then
        return #player.room.logic:getEventsOfScope(GameEvent.Damage, 2, function (e)
          local damage = e.data[1]
          if damage and damage.from and target == damage.from then
            return true
          end
        end, Player.HistoryTurn) == 1
      end
    end
  end,
  on_cost =  function(self, event, target, player, data)
    if event == fk.DamageCaused then
      return true
    else
      return player.room:askForSkillInvoke(player, self.name, nil, "#ev__yuelang::"..target.id)
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.DamageCaused then
      data.damage = data.damage + 1
    else
      target:drawCards(1, self.name)
    end
  end,

  --[[refresh_events = {fk.AfterCardUseDeclared},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(self.name) and target == player then
      return #player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function(e)
        local use = e.data[1]
        return use.from == player.id end, Player.HistoryTurn) == 1
    end
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setCardMark(data.card, "yuelang-turn", 1)
  end,]]
}


local ev__yongchao = fk.CreateTriggerSkill{
  name = "ev__yongchao",
  frequency = Skill.Wake,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and player.phase == Player.Start and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  can_wake = function(self, event, target, player, data)
    local friends = table.filter(player.room:getOtherPlayers(player, true, true), function(p) return player.role == p.role or (player.role == "lord" and p.role == "loyalist") end)
    return #friends > 0 and table.every(friends, function(p) return p.dead end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeMaxHp(player, 2)
    room:recover({
      who = player,
      num = 2,
      recoverBy = player,
      skillName = self.name
    })
    if player:getHandcardNum() < player.hp then
      player:drawCards(player.hp - player:getHandcardNum(), self.name)
    end
  end,
}

Skadi:addSkill(ev__yuelang)
Skadi:addSkill(ev__yongchao)

Fk:loadTranslationTable{
  ["ev__skadi"] = "斯卡蒂",
  ["designer:ev__skadi"] = "zengyouyu",
  ["ev__yuelang"] = "跃浪",
  [":ev__yuelang"] = "当你<font color=\"#D2042D\">{于当前回合内首次}</font>造成伤害时，你令此伤害+1。当一名角色于其回合内首次造成伤害后，若此伤害大于1点，你可令其摸一张牌。",
  ["#ev__yuelang"] = "跃浪：你可令%dest摸一张牌",
  ["ev__yongchao"] = "涌潮",
  [":ev__yongchao"] = "觉醒技，准备阶段，若与你阵营相同且不为主教的其他角色均已死亡，你增加2点体力上限，回复2点体力，将手牌补至体力值，删除<font color=\"#D2042D\">{ }</font>里的描述。",

  ["$ev__yuelang1"] = "和我面对过的灾厄相比，你们也太弱了。",
  ["$ev__yuelang2"] = "谁知道潮湿的海草间蛰伏着什么？",
  ["$ev__yuelang3"] = "别眨眼，你会错过自己的死状。",
  ["$ev__yongchao"] = "我习惯了独行。",
  ["~ev__skadi"] = "这种程度的不幸，也只是个开始罢了。",
}

local xiangling = General(extension, "ev__xiangling", "ev", 4, 4, General.Female)

local guobapenhuo = fk.CreateActiveSkill{
  name = "guobapenhuo",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and Self:canPindian(Fk:currentRoom():getPlayerById(to_select))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local pindian = player:pindian({target}, self.name)
    local winner = nil
    if pindian.results[target.id].winner == player then
      winner = player
    elseif pindian.results[target.id].winner == target then
      winner = target
    end
    local cards = {pindian.fromCard:getEffectiveId(), pindian.results[target.id].toCard:getEffectiveId()}
    if winner ~= nil then
      local ids, choice = U.askforChooseCardsAndChoice(winner, cards, {"OK", "cancel"}, self.name, "#guobapenhuo")
      if choice ~= "cancel" then
        room:moveCardTo(ids, Card.PlayerHand, winner, fk.ReasonJustMove, self.name, "", true)
        local color = Fk:getCardById(ids[1]):getColorString()
        room:setPlayerMark(player, "guobapenhuo_slash-turn", color)--会覆盖掉上一次
        room:setPlayerMark(target, "guobapenhuo_prohibit-turn", color)
      end
    end
  end,
}

local guobapenhuo_filter = fk.CreateFilterSkill{
  name = "#guobapenhuo_filter",
  card_filter = function(self, to_select, player)
    if table.contains(player.player_cards[Player.Hand], to_select.id) and player:getMark("guobapenhuo_slash-turn") ~= 0 then
      local color = player:getMark("guobapenhuo_slash-turn")
      return to_select:getColorString() == color
    end
  end,
  view_as = function(self, to_select)
    return Fk:cloneCard("ev_fire__slash", to_select.suit, to_select.number)
  end,
}

local guobapenhuo_prohibit = fk.CreateProhibitSkill{
  name = "#guobapenhuo_prohibit",
  prohibit_use = function(self, player, card)
    if player:getMark("guobapenhuo_prohibit-turn") ~= 0 then
      local color = player:getMark("guobapenhuo_prohibit-turn")
      return card:getColorString() == color
    end
  end,
}

local wanminbaiwei = fk.CreateTriggerSkill{
  name = "wanminbaiwei",
  frequency = Skill.Compulsory,
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and data.card and data.card.trueName == "slash"
    and not data.to:isNude()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local id = EV.askForCardChosen(room, player, data.to, "hes", self.name)
    room:obtainCard(player.id, id, false, fk.ReasonPrey)
    if id > 0 then
      local card = Fk:getCardById(id)
      if data.card.suit == card.suit then
        local to = room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1,
        "#wanminbaiwei-choose:::"..card:toLogString(), self.name, true)
        if #to > 0 then
          room:moveCardTo(id, Card.PlayerHand, room:getPlayerById(to[1]), fk.ReasonGive, self.name, nil, false, player.id)
          local returncard = room:askForCard(room:getPlayerById(to[1]), 2, 2, true, self.name, true, ".", "#wanminbaiwei-return::"..player.id)
          if #returncard > 0 then
            room:moveCardTo(returncard, Card.PlayerHand, player, fk.ReasonGive, self.name, nil, false, player.id)
          end
        end
      else
        room:moveCardTo(id, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true)
      end
    end
  end,
}
guobapenhuo:addRelatedSkill(guobapenhuo_filter)
guobapenhuo:addRelatedSkill(guobapenhuo_prohibit)
xiangling:addSkill(guobapenhuo)
xiangling:addSkill(wanminbaiwei)

Fk:loadTranslationTable{
  ["ev__xiangling"] = "香菱",
  ["designer:ev__xiangling"] = "zengyouyu",
  ["guobapenhuo"] = "锅巴喷火",
  [":guobapenhuo"] = "阶段技，你可与一名其他角色拼点，拼点赢的角色可获得一张拼点的牌，则本回合内：你与之颜色相同的手牌视为火【杀】，对方不能使用与之颜色相同的牌。",
  ["#guobapenhuo"] = "你可获得一张拼点的牌",
  ["#guobapenhuo_filter"] = "锅巴喷火",
  ["#guobapenhuo_prohibit"] = "锅巴喷火",
  ["wanminbaiwei"] = "万民百味",
  [":wanminbaiwei"] = "锁定技，当你使用【杀】造成伤害后，你获得受伤角色的一张牌，若此牌与此【杀】花色不同/相同，你弃置之/将之交给一名角色，然后其可交给你两张牌。",
  ["#wanminbaiwei-choose"] = "请选择将%arg交给的角色",
  ["#wanminbaiwei-return"] = "你可以交给%dest两张牌",
}

return extension